package com.carnation.servlet;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.carnation.service.FileService;
import com.carnation.service.impl.FileServiceImpl;

public class DownLocalFileServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(DownLocalFileServlet.class);
	
	@Override
	protected void doPost(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException{
		String fakePath = httpServletRequest.getParameter("path");
		String filename = httpServletRequest.getParameter("filename");
		FileService fileService = new FileServiceImpl();
		String realpath = fileService.getRealPath(fakePath);
		InputStream is = fileService.getFileInputStream(realpath, filename);
		if(is == null){
			httpServletResponse.setCharacterEncoding("UTF-8");
			httpServletResponse.getWriter().write("找不到对应的文件");
			httpServletResponse.getWriter().close();
		}
		else{
			httpServletResponse.reset();
			httpServletResponse.setContentType("application/ms-xdownload");
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("UTF-8"),"ISO-8859-1") + "\"");
			ServletOutputStream out =httpServletResponse.getOutputStream();
			BufferedOutputStream bout = new BufferedOutputStream(out);
			int read = -1;
			byte[] buff = new byte[1024];
			while((read=is.read(buff)) != -1){
				bout.write(buff, 0, read);
			}
			is.close();
			bout.close();
			out.close();
			logger.info("IP地址为" + httpServletRequest.getRemoteAddr()  + "下载了文件:" + filename);
		}
	}
}
